package org.example.spi;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.registry.Registry;
import org.example.serializer.Serializer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description loaderMap:存储的是
 * @author sats@jz
 * @date 2024年12月30日 13:47
 */
@Slf4j
public class SpiLoader {
    // 存储已经加载的类，接口->key->实现类
    /**
     * @description
     * loaderMap： key:接口名的权限路径名字，org.example.registry.XXXXX，
     *            Value:org.example.registry.XXXXX文件夹下的所有类
     * Map<String, Class<?>：
     * key: 文件中jdk=XXX， 钱买你的kdk
     * value: 文件中的XXX， 类名， Class.forName(XXX)
     * @author: sats@jz
     * @param  : null - [null]
     * @return : null
     **/
    private static Map<String, Map<String, Class<?>>> loaderMap = new ConcurrentHashMap<>();

    // 对象实例缓存
    private static Map<String, Object> instanceCache = new ConcurrentHashMap<>();

    // 系统SPI目录
    private static final String RPC_SYSTEM_SPI_DIR = "META-INF.rpc/system/";

    // 自定义SPI目录
    private static final String RPC_CUSTOM_SPI_DIR = "META-INF.rpc/custom/";

    // 扫描路径
    private static final String[] SCAN_DIRS = new String[]{
            RPC_SYSTEM_SPI_DIR,
            RPC_CUSTOM_SPI_DIR
    };

    // 动态加载类的列表
    private static final List<Class<?>> LOAD_CLASS_LIST = Arrays.asList(Serializer.class, Registry.class);

    // 加载所有类型
    public static void loadAll() {
        for (Class<?> clazz : LOAD_CLASS_LIST) {
            load(clazz);
        }
    }

    // 加载指定
    public static <T> T getInstance(Class<?> tClazz, String key) {
        String tClassName = tClazz.getName();
        Map<String, Class<?>> keyClassMap = loaderMap.get(tClassName);
        if (keyClassMap == null) {
            throw new RuntimeException(String.format("SpiLoader 未加载 %s 类型", tClassName));
        }
        if (!keyClassMap.containsKey(key)) {
            throw new RuntimeException(String.format("SpiLoader 未加载 %s 类型的 %s 实现", tClassName, key));
        }
        Class<?> impClass = keyClassMap.get(key);
        if(!instanceCache.containsKey(impClass.getName())){
            try {
                instanceCache.put(impClass.getName(), impClass.getConstructor().newInstance());
            } catch (Exception e){
                throw new RuntimeException(String.format("SpiLoader %s 实现类实例化失败", impClass.getName()));
            }
        }
        return (T) instanceCache.get(impClass.getName());
    }

    public static Map<String, Class<?>> load(Class<?> loadClass){
        log.info("加载类型为 {} 的 SPI", loadClass.getName());
        // 扫描路径， 用户的高于系统
        Map<String, Class<?>> keyClassMap = new HashMap<>();
        for (String scanDir : SCAN_DIRS) {
            String t = scanDir + loadClass.getName();
            List<URL> resources = ResourceUtil.getResources(t);
            for (URL resource : resources){
                try {
                    InputStreamReader inputStreamReader = new InputStreamReader(resource.openStream());
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line;
                    while((line = bufferedReader.readLine()) != null){
                        String[] strArray = line.split("=");
                        if (strArray.length > 1){
                            String key = strArray[0];
                            String className = strArray[1];
                            keyClassMap.put(key, Class.forName(className));
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        loaderMap.put(loadClass.getName(), keyClassMap);
        return keyClassMap;
    }
}
